#define MINIDUMP_API __declspec(dllexport)

#include "minidump.h"
#include <Windows.h>
#include <DbgHelp.h>
#include <string>
#include <ctime>
#pragma comment(lib,"dbghelp.lib")
using namespace std;

// Define unhandled exception handle function.
LONG WINAPI ExceptionFilter(struct _EXCEPTION_POINTERS *pExceptionPointers)
{
	time_t t = time(0);
	char timeBuffer[64] = {0};
	strftime(timeBuffer,sizeof(timeBuffer),"%Y%m%d%H%M%S",localtime(&t));
	string strTime(timeBuffer);

	DWORD dwProcessId = GetCurrentProcessId();
	HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,dwProcessId);
	if (hProcess != INVALID_HANDLE_VALUE)
	{
		char szPath[MAX_PATH];
		if (GetModuleFileName(NULL,szPath,sizeof(szPath)))
		{
			string strDumpFileName(szPath);
			strDumpFileName += strTime;
			strDumpFileName += TEXT(".dmp");
			HANDLE hDumpFile = CreateFile(strDumpFileName.c_str(),FILE_ALL_ACCESS,0,NULL,CREATE_ALWAYS,NULL,NULL);
			if (hDumpFile != INVALID_HANDLE_VALUE)
			{
				MINIDUMP_EXCEPTION_INFORMATION exception_information;
				exception_information.ThreadId = GetCurrentThreadId();
				exception_information.ExceptionPointers = pExceptionPointers;
				exception_information.ClientPointers = TRUE;
				MiniDumpWriteDump(hProcess,dwProcessId,hDumpFile,/*MiniDumpNormal*/MiniDumpWithFullMemory,&exception_information,NULL,NULL);
				CloseHandle(hDumpFile);
			}
		}
		CloseHandle(hProcess);
	}
	return EXCEPTION_EXECUTE_HANDLER;
}

void installCrashProcCtrl()
{
	//Set unhandled exception callback function.
	SetUnhandledExceptionFilter(ExceptionFilter);
}